package com.wx.clazzloader;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @description: 自定义类加载器
 * 类加载器
 * 1. 重写findClass() 找到.class文件，转化对应的字节数组
 * 2. 调用defineClass() 将字节数组，生成对应java.lang.Class 对象
 * @author: wangxun
 * @createDate: 2021/5/8
 * @version: 1.0
 */
@Slf4j
public class MyClassLoader extends ClassLoader {
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        // 1. 找到对应的class文件
        final File file = new File("E:\\clazz\\Env.class");
        Class<?> aClass = null;
        try {
            RandomAccessFile fis = new RandomAccessFile(file, "r");
            FileChannel channel = fis.getChannel();
            MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
            int length = (int) channel.size();
            byte[] bytes = new byte[length];
            map.get(bytes);

            aClass = defineClass(null, bytes, 0, length);
            log.info(aClass.getName());

        } catch (Exception e) {
            e.printStackTrace();
        }

        return aClass;
    }
}
